'''
Created on Apr 20, 2012

@author: peng
'''
# -*- coding: utf-8 -*-
# Daemon module
# @auth     jaypei
# @email    jaypei97159@gmail.com
 
import sys, os, time, atexit, signal
 
class Daemon(object):
    """A generic daemon class.
 
    Usage: subclass the daemon class and override the run() method."""
 
    def __init__(self, pidfile, def_output=False):
        self.pidfile = pidfile
        self.def_output = def_output
 
    def daemonize(self):
        """Deamonize class. UNIX double fork mechanism."""
 
        try:
            pid = os.fork()
            if pid > 0:
                # exit first parent
                sys.exit(0)
        except OSError, err:
            sys.stderr.write('fork #1 failed: %s\n' % str(err))
            sys.exit(1)
 
        # decouple from parent environment
        os.chdir('/')
        os.setsid()
        os.umask(0)
 
        # do second fork
        try:
            pid = os.fork()
            if pid > 0:
 
                # exit from second parent
                sys.exit(0)
        except OSError, err:
            sys.stderr.write('fork #2 failed: %s\n' % str(err))
            sys.exit(1)
 
        # redirect standard file descriptors
        if not self.def_output:
            sys.stdout.flush()
            sys.stderr.flush()
            si = open(os.devnull, 'r')
            so = open(os.devnull, 'a+')
            se = open(os.devnull, 'a+')
 
            os.dup2(si.fileno(), sys.stdin.fileno())
            os.dup2(so.fileno(), sys.stdout.fileno())
            os.dup2(se.fileno(), sys.stderr.fileno())
 
        # write pidfile
        atexit.register(self.delpid)
 
        pid = str(os.getpid())
        fp = open(self.pidfile, 'w+')
        fp.write(pid + '\n')
        fp.close()
 
    def delpid(self):
        os.remove(self.pidfile)
 
    def start(self):
        """Start the daemon."""
 
        # Check for a pidfile to see if the daemon already runs
        try:
            fp = open(self.pidfile, 'r')
            pid = int(fp.read().strip())
            fp.close()
        except IOError:
            pid = None
 
        if pid:
            message = "pidfile %s already exist. " + \
                    "Daemon already running?\n"
            sys.stderr.write(message % self.pidfile)
            sys.exit(1)
 
        # Start the daemon
        self.daemonize()
        self.run()
 
    def stop(self):
        """Stop the daemon."""
 
        # Get the pid from the pidfile
        try:
            fp = open(self.pidfile, 'r')
            pid = int(fp.read().strip())
            fp.close()
        except IOError:
            pid = None
 
        if not pid:
            message = "pidfile %s does not exist. " + \
                    "Daemon not running?\n"
            sys.stderr.write(message % self.pidfile)
            return  # not an error in a restart
 
        # Try killing the daemon process    
        try:
            while 1:
                os.kill(pid, signal.SIGTERM)
                time.sleep(0.1)
        except OSError, err:
            e = str(err.args)
            if e.find("No such process") > 0:
                if os.path.exists(self.pidfile):
                    os.remove(self.pidfile)
            else:
                print (str(err.args))
                sys.exit(1)
 
    def restart(self):
        """Restart the daemon."""
        self.stop()
        self.start()
 
    def status(self):
        """Check the status of the process (running | not running)"""
        try:
            pf = file(self.pidfile, 'r')
            pid = int(pf.read().strip())
            pf.close()
            os.kill(int(pid), 0)
        except OSError:
            message = "%s process is not running." % self.name
            print message
        except IOError:
            message = "PID file not found. Process may not be running."
            print message
        else:
            message = "%s process is running with PID: %s" % (self.name, pid)
            print message
 
    def run(self):
        """You should override this method when you subclass Daemon.
 
        It will be called after the process has been daemonized by 
        start() or restart()."""
        raise NotImplementedError
 
    def doShell(self, argv):
        prog_name = argv[0]
 
        def usage():
            print >> sys.stderr, "Usage: %(prog)s start|stop|restart" % {
                    "prog": prog_name }
            sys.exit(0)
 
        if len(argv) != 2:
            usage()
            print
 
        command = argv[1]
        if command == "start":
            self.start()
        elif command == "stop":
            self.stop()
        elif command == "restart":
            self.restart()
        else:
            usage()
